/**
 * @description dict字典表store
 */

import {
  getSimpleDictDataList,
  DictDataVO,
  getDictTypeTree,
} from '@/api/system/dict/dict.data'

export const useDictStore = defineStore('dict', {
  state: () => ({
    // dictTypes: [] as DictDataVO[],
    dictTypesMap: new Map<number | string, DictDataVO[]>(),
  }),
  getters: {
    /**
     * @description 获取具体某个字典值
     * @param dictType {number | string} 字典类型
     */
    getDictType: (state) => {
      return (dictType: number | string): DictDataVO[] =>
        state.dictTypesMap.get(dictType) || []
    },
    /**
     * @description 通过value获取对应的label
     * @param dictType {number | string} 字典类型
     * @param value {number | string} 字典value
     */
    getDictLabelForValue: (state) => {
      return (
        dictType: number | string,
        value: number | string
      ): string | undefined => {
        const dictItems = state.dictTypesMap.get(dictType) || []
        return dictItems.find((item) => item.value === value?.toString())?.label
      }
    },
    /**
     * @description 通过value获取对应的数据对象
     * @param dictType {number | string} 字典类型
     * @param value {number | string} 字典value
     */
    getDictForValue: (state) => {
      return (
        dictType: number | string,
        value: number | string
      ): DictDataVO | undefined => {
        const dictItems = state.dictTypesMap.get(dictType) || []
        return dictItems.find((item) => item.value === value?.toString())
      }
    },
    /**
     * @description 通过value查找树形结构中对应的label
     * @param dictType {number | string} 字典类型
     * @param value {number | string} 字典value
     */
    getLabelForValueInTree: (state) => {
      return (
        dictType: number | string,
        value: number | string
      ): string | undefined => {
        const dictItems = state.dictTypesMap.get(dictType) || []

        // 递归查找树形结构中的value
        const findLabelInTree = (items: DictDataVO[]): string | undefined => {
          for (const item of items) {
            if (item.value === value?.toString()) {
              return item.label
            }
            if (item.children && item.children.length > 0) {
              const foundLabel = findLabelInTree(item.children)
              if (foundLabel) {
                return foundLabel
              }
            }
          }
          return undefined
        }

        return findLabelInTree(dictItems)
      }
    },
  },
  actions: {
    /**
     * @description 获取全部字典表
     */
    async getAllDictTypes() {
      try {
        // const response: any = await getSimpleDictDataList()
        const response: any = await getDictTypeTree({ parentId: 0 })
        if (
          response.code === 0 &&
          response.data &&
          Array.isArray(response.data.children)
        ) {
          const tempMap = new Map<number | string, DictDataVO[]>()
          response.data.children.forEach((parentItem) => {
            const { dictType, children } = parentItem
            if (Array.isArray(children)) {
              // 如果 tempMap 已有该 dictType 的数据，进行合并
              const existingChildren = tempMap.get(dictType) || []
              tempMap.set(dictType, existingChildren.concat(children))
            }
          })
          this.dictTypesMap = tempMap // 更新state中的dictTypesMap
          // console.log('全部字典', this.dictTypesMap)
        } else {
          console.error('获取字典数据错误:', response.message)
        }
      } catch (error) {
        console.error('获取字典数据异常:', error)
      }
    },
  },
})
